package cn.appsys.controller.backend;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.appsys.pojo.BackendUser;
import cn.appsys.service.backend.BackendUserService;
import cn.appsys.tools.Constants;

@Controller
@RequestMapping("/manager")
public class UserLoginController {

	private Logger logger = Logger.getLogger(UserLoginController.class);

	@Resource
	private BackendUserService backendUserService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "backendlogin";
	}

	@RequestMapping(value = "/dologin", method = RequestMethod.POST)
	public String doLogin(@RequestParam String userCode, @RequestParam String userPassword,
			HttpServletRequest request) {
		logger.debug("userCode ==========>：" + userCode);
		logger.debug("userPassWord ===========>：" + userPassword);

		BackendUser backendUser = backendUserService.login(userCode, "USER_TYPE");
		if (backendUser != null) {
			if (userPassword.equals(backendUser.getUserPassword())) {
				request.getSession().setAttribute(Constants.USER_SESSION, backendUser);
				return "redirect:main";
			}
			request.setAttribute("error", "密码不正确！");
			return "backendlogin";
		}
		request.setAttribute("error", "没有该账户！");
		return "backendlogin";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		request.removeAttribute("error");
		request.getSession().removeAttribute(Constants.USER_SESSION);
		return "backendlogin";
	}

	@RequestMapping("/main")
	public String main() {
		return "backend/main";
	}
}
